package com.example.bootintegration.datasource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.type.StandardAnnotationMetadata;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.config.BootstrapMode;
import org.springframework.data.repository.config.DefaultRepositoryBaseClass;
import org.springframework.data.repository.query.QueryLookupStrategy;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

class JpaRepositoryAnnotationMetadata extends StandardAnnotationMetadata {
    private static final Logger log = LoggerFactory.getLogger(JpaRepositoryAnnotationMetadata.class);
    private final Map<String, Object> attributes;

    public JpaRepositoryAnnotationMetadata(String dataSourceName, Environment env) {
        super(JpaRepositoryAnnotationMetadata.class);
        this.attributes = this.initAttributes(dataSourceName, env);
    }

    // 可以直接写注解@EnableJpaRepositories来配置属性，这里可能为了自定义，因此覆盖了这个方法，采用手动设置属性的方式
    @Override
    public Map<String, Object> getAnnotationAttributes(String annotationName) {
        return this.attributes;
    }

    private Map<String, Object> initAttributes(String dataSourceName, Environment env) {
        Map<String, Object> map = new LinkedHashMap();
        map.put("value", new String[0]);
        map.put("repositoryFactoryBeanClass", JpaRepositoryFactoryBean.class);
//        Class repositoryBaseClass = env.getProperty("synnex.datasource." + dataSourceName + ".repositoryBaseClass");
        map.put("repositoryBaseClass", DefaultRepositoryBaseClass.class);
        map.put("entityManagerFactoryRef", dataSourceName + "EntityManagerFactory");
        map.put("transactionManagerRef", dataSourceName + "TransactionManager");
        String basePackages = env.getProperty("boot.datasource." + dataSourceName + ".repository", "com.synnex.repositoryLostInParadise");
        map.put("basePackages", new String[] {basePackages, "boot.datasource.jpa.repository"});
        map.put("basePackageClasses", new Class[0]);
        map.put("includeFilters", new AnnotationAttributes[0]);
        map.put("excludeFilters", new AnnotationAttributes[0]);
        map.put("repositoryImplementationPostfix", "Impl");
        map.put("namedQueriesLocation", "");
        map.put("queryLookupStrategy", QueryLookupStrategy.Key.CREATE_IF_NOT_FOUND);
        map.put("considerNestedRepositories", false);
        map.put("enableDefaultTransactions", true);
        map.put("bootstrapMode", BootstrapMode.DEFAULT);
        map.put("escapeCharacter", '\\');
        log.info("repository configuration, dataSourceName: {}, configuration: {}", dataSourceName, map);
        return Collections.unmodifiableMap(map);
    }



}